package com.texaco.chapasFutbol.camera;

import org.andengine.engine.camera.ZoomCamera;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.detector.PinchZoomDetector;
import org.andengine.input.touch.detector.PinchZoomDetector.IPinchZoomDetectorListener;

import com.texaco.chapasFutbol.R;

import android.app.Activity;

public class ZoomHandler implements IPinchZoomDetectorListener{

	private PinchZoomDetector pinchZoomDetector;
	private float pinchZoomStartedCameraZoomFactor;
	private ZoomCamera camera;
	private Activity activity;

	public ZoomHandler(ZoomCamera camera, Activity activity){
		this.activity = activity;
		this.camera = camera;
		this.pinchZoomDetector = new PinchZoomDetector(this);
	}
	public void onPinchZoomStarted(PinchZoomDetector pPinchZoomDetector,
			TouchEvent pSceneTouchEvent) {
		this.pinchZoomStartedCameraZoomFactor = camera.getZoomFactor();
	}

	public void onPinchZoom(PinchZoomDetector pPinchZoomDetector,
			TouchEvent pTouchEvent, float pZoomFactor) {
		if(this.pinchZoomStartedCameraZoomFactor * pZoomFactor <= getMaxFactor() && 
				this.pinchZoomStartedCameraZoomFactor * pZoomFactor >= getMinFactor()){
			camera.setZoomFactor(this.pinchZoomStartedCameraZoomFactor * pZoomFactor);
		}else if(this.pinchZoomStartedCameraZoomFactor * pZoomFactor < getMinFactor()){
			camera.setZoomFactor(getMinFactor());
		}else{
			camera.setZoomFactor(getMaxFactor());
		}
	}

	public void onPinchZoomFinished(PinchZoomDetector pPinchZoomDetector,
			TouchEvent pTouchEvent, float pZoomFactor) {
		if(this.pinchZoomStartedCameraZoomFactor * pZoomFactor <= getMaxFactor() && 
				this.pinchZoomStartedCameraZoomFactor * pZoomFactor >= getMinFactor()){
			camera.setZoomFactor(this.pinchZoomStartedCameraZoomFactor * pZoomFactor);
		}else if(this.pinchZoomStartedCameraZoomFactor * pZoomFactor < getMinFactor()){
			camera.setZoomFactor(getMinFactor());
		}else{
			camera.setZoomFactor(getMaxFactor());
		}
	}
	
	public PinchZoomDetector getPinchZoomDetector() {
		return pinchZoomDetector;
	}
	public void setPinchZoomDetector(PinchZoomDetector pinchZoomDetector) {
		this.pinchZoomDetector = pinchZoomDetector;
	}
	
	private float getMaxFactor() {
		return (float)this.activity.getResources().getInteger(R.integer.max_zoom_factor)/100f ;
	}
	private float getMinFactor() {
		return (float)this.activity.getResources().getInteger(R.integer.min_zoom_factor)/100f ;
	}
}
